import React, { useContext, useState } from 'react';
import { Empty, Input, message } from 'antd';
import EmployeeDetailContext from '@/pages/Organization/EmployeeManage/EmployeeDetail/store/context';
import { useDeepCompareEffect } from 'react-use';
import { parseEmployeeExtendInfoList } from '@/pages/Organization/EmployeeManage/components/EmployeeInfoSections/util';
import { defaultFormatResult, useRequest } from '@/hooks';
import { getEmployeeFieldConfig } from '@/pages/Organization/EmployeeManage/services';
import FormContainer, { FormItem } from './FormContainer';

/**
 * 员工档案 - 工资社保 - 个税专项扣除
 */
const PersonalTaxSpecialDeductionSection = ({ formData, readonly, saveAction, onChange }) => {
    const employeeDetailContext = useContext(EmployeeDetailContext);
    const currentEmployeeCountryCode = employeeDetailContext?.employeeInfo?.countryNameCode;

    // 因为国际化的字段是在 employeeExtendInfoList 数组里面, 这里将它打散到 formData 里面
    const [parsedFormData, setParsedFormData] = useState();
    // 获取国际化字段的默认配置
    const { data: employeeFieldConfig } = useRequest(
        () =>
            getEmployeeFieldConfig({
                countryNameCode: currentEmployeeCountryCode,
                groupCode: 'personalTaxSpecialDeduction'
            }),
        {
            ready: !!currentEmployeeCountryCode,
            ...defaultFormatResult
        }
    );

    // mounted
    useDeepCompareEffect(() => {
        const employeeExtendInfoMap = parseEmployeeExtendInfoList(
            formData?.employeeExtendInfoList ?? [],
            currentEmployeeCountryCode
        );
        const combineData = { ...formData, ...employeeExtendInfoMap };
        setParsedFormData(combineData);
    }, [formData]);

    // 提交
    const { run: submitRun } = useRequest(submitData => saveAction && saveAction(submitData), {
        manual: true
    });
    // 保存
    const handleSubmit = async values => {
        // 扩展字段处理
        const employeeExtendInfoList = employeeFieldConfig.map(item => ({
            ...item,
            fieldValue: Number(values[item.fieldCode])
        }));
        const submitData = Object.assign({
            ...formData,
            employeeExtendInfoList
        });
        // 提交
        const res = await submitRun(submitData);
        if (res.code === 10000) {
            message.success(res.msg);
            onChange(submitData);
        } else {
            message.error(res.msg);
        }
    };

    const validateMoney = (rule, value, callback) => {
        if (!/[0-9.]+/.test(value)) {
            callback('只能输入数字');
        } else if (value > 1000000 || value < 0) {
            callback('金额不能大于 1000000');
        } else {
            callback();
        }
    };

    return (
        // render
        <FormContainer
            title="个税专项扣除"
            hasEditAuth={!readonly && !!saveAction && !!employeeFieldConfig}
            flexLayout
            onSubmit={handleSubmit}
        >
            {({ getFieldDecorator }) =>
                parsedFormData ? (
                    <>
                        <FormItem
                            label="子女教育"
                            show={currentEmployeeCountryCode === 'CN'}
                            normalComponent={() => (
                                <div className="multiLineText">{parsedFormData?.childrenEdu || '--'}</div>
                            )}
                            editComponent={() =>
                                getFieldDecorator('childrenEdu', {
                                    initialValue: parsedFormData?.childrenEdu ?? undefined,
                                    rules: [
                                        {
                                            validator: validateMoney
                                        }
                                    ]
                                })(<Input type="number" addonAfter="元" placeholder="请填写子女教育" allowClear />)
                            }
                        />
                        <FormItem
                            label="继续教育"
                            show={currentEmployeeCountryCode === 'CN'}
                            normalComponent={() => (
                                <div className="multiLineText">{parsedFormData?.continueEdu || '--'}</div>
                            )}
                            editComponent={() =>
                                getFieldDecorator('continueEdu', {
                                    initialValue: parsedFormData?.continueEdu ?? undefined,
                                    rules: [
                                        {
                                            validator: validateMoney
                                        }
                                    ]
                                })(<Input type="number" addonAfter="元" placeholder="请填写继续教育" allowClear />)
                            }
                        />
                        <FormItem
                            label="住房贷款利息"
                            show={currentEmployeeCountryCode === 'CN'}
                            normalComponent={() => (
                                <div className="multiLineText">{parsedFormData?.houseLoan || '--'}</div>
                            )}
                            editComponent={() =>
                                getFieldDecorator('houseLoan', {
                                    initialValue: parsedFormData?.houseLoan ?? undefined,
                                    rules: [
                                        {
                                            validator: validateMoney
                                        }
                                    ]
                                })(<Input type="number" addonAfter="元" placeholder="请填写住房贷款利息" allowClear />)
                            }
                        />
                        <FormItem
                            label="住房租金"
                            show={currentEmployeeCountryCode === 'CN'}
                            normalComponent={() => (
                                <div className="multiLineText">{parsedFormData?.houseRent || '--'}</div>
                            )}
                            editComponent={() =>
                                getFieldDecorator('houseRent', {
                                    initialValue: parsedFormData?.houseRent ?? undefined,
                                    rules: [
                                        {
                                            validator: validateMoney
                                        }
                                    ]
                                })(<Input type="number" addonAfter="元" placeholder="请填写住房租金" allowClear />)
                            }
                        />
                        <FormItem
                            label="赡养老人"
                            show={currentEmployeeCountryCode === 'CN'}
                            normalComponent={() => (
                                <div className="multiLineText">{parsedFormData?.supportElder || '--'}</div>
                            )}
                            editComponent={() =>
                                getFieldDecorator('supportElder', {
                                    initialValue: parsedFormData?.supportElder ?? undefined,
                                    rules: [
                                        {
                                            validator: validateMoney
                                        }
                                    ]
                                })(<Input type="number" addonAfter="元" placeholder="请填写赡养老人" allowClear />)
                            }
                        />
                        <FormItem
                            label="大病医疗"
                            show={currentEmployeeCountryCode === 'CN'}
                            normalComponent={() => (
                                <div className="multiLineText">{parsedFormData?.seriousIllness || '--'}</div>
                            )}
                            editComponent={() =>
                                getFieldDecorator('seriousIllness', {
                                    initialValue: parsedFormData?.seriousIllness ?? undefined,
                                    rules: [
                                        {
                                            validator: validateMoney
                                        }
                                    ]
                                })(<Input type="number" addonAfter="元" placeholder="请填写大病医疗" allowClear />)
                            }
                        />
                    </>
                ) : (
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                )
            }
        </FormContainer>
    );
};

export default PersonalTaxSpecialDeductionSection;
